<template>
  <div>
    <video ref="video" autoplay></video>
    <button @click="switchCamera">Switch Camera</button>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      stream: null,
      videoDevices: [],
      selectedDeviceIndex: 0 // Index of the currently selected camera
    }
  },
  mounted() {
    // Get list of available media devices
    navigator.mediaDevices
      .enumerateDevices()
      .then((devices) => {
        this.videoDevices = devices.filter((device) => device.kind === 'videoinput')
        this.startCamera() // Start the camera by default
      })
      .catch((error) => {
        console.error('Error getting media devices: ', error)
      })
  },
  methods: {
    async startCamera() {
      if (this.stream) {
        this.stopCamera() // Stop previous camera stream if any
      }
      const deviceId = this.videoDevices[this.selectedDeviceIndex].deviceId
      try {
        this.stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: deviceId } })
        this.$refs.video.srcObject = this.stream
      } catch (error) {
        console.error('Error accessing camera: ', error)
      }
    },
    stopCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop())
        this.stream = null
      }
    },
    switchCamera() {
      this.selectedDeviceIndex = (this.selectedDeviceIndex + 1) % this.videoDevices.length
      this.startCamera()
    }
  }
}
</script>
  
  <style scoped>
/* Add your styles here */
</style>
  